<template>
  <div class="frame">
    <el-card
      v-for="(blog, index) in blogList"
      :key="blog.id"
      class="blog-card"
    >
      <div class="blog-title">
        <router-link :to="{ name: 'blog', query: {id: blog.id} }" class="title-url">{{ blog.title }}</router-link>
      </div>
      <div class="blog-meta">
        <div class="left-info">
          <router-link :to="{ name: 'author', params: {id: blog.author_id} }">{{ blog.author }}</router-link>
          <span class="info-item">{{ blog.created_at }}</span>
          <div class="blog-tags">
            <el-tag
              v-for="tag in blog.tags"
              :key="tag"
              size="small"
              effect="light"
              @click="handleTagClick(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div class="right-info">
          <el-icon class="icon-view">
            <View />
          </el-icon>
          <span class="info-item">浏览-{{ blog.views }}</span>
          <el-divider
            class="el-divider-vertical"
            direction="vertical"
          ></el-divider>
          <el-icon class="icon-star">
            <StarFilled />
          </el-icon>
          <span class="info-item">赞-{{ blog.stars }}</span>
        </div>
      </div>

      <div class="blog-content">
        <p class="content-text">{{ blog.content }}</p>
      </div>
    </el-card>
    <div class="pagination-container">
      <el-pagination
        background
        v-model:current-page="currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        :page-count="totalPages"
        :total="totalBlogs"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @onUpdate:currentPage="handleUpdateCurrentPage(currentPage)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from "vue";

  import { useRouter } from "vue-router";
  import { apiGetBlogs } from "@/api/blog";
  import type { Blog, BlogsResponse } from "@/types/blog";

  const router = useRouter();
  // 分页参数
  let currentPage = ref(1); // 当前页码
  let pageSize = ref(5);
  let totalPages = ref(0);
  let totalBlogs = ref(0);

  let blogList = ref<Blog[]>([]);
  let blogCount = 0; // 当前页面获取到的blog数目
  let firstBlogId = 0;
  let lastBlogId = 0;

  // 计算当前页面显示的博客，computed 作用
  // 自动更新: 当 computed 依赖的数据发生变化时，它会自动重新计算。
  // 缓存结果: computed 会在其依赖未发生变化时缓存结果，避免不必要的计算
  // let paginatedBlogs = computed(() => {
  //   const startIndex = (currentPage.value - 1) * pageSize.value;
  //   const endIndex = startIndex + blogCount;
  //   // firstBlogId = startIndex;
  //   // lastBlogIdTemp = lastBlogId;
  //   // lastBlogId = blogList.value[endIndex - 1]?.id || 0;
  //   return blogList.value.slice(startIndex, endIndex); // 左闭右开，end不需要-1
  // });

  // 处理分页变化
  async function getBlogs(blogId: number) {
    // 假设需要执行其他操作，如重新获取数据并更新 UI
    try {
      const rsp: BlogsResponse = await apiGetBlogs(blogId, pageSize.value);
      if (rsp.blog_count > 0) {
        blogList.value = rsp.blogs;
        blogCount = rsp.blog_count;
        totalBlogs.value = rsp.total_count;
        totalPages.value = Math.floor((rsp.total_count + pageSize.value - 1) / pageSize.value);

        firstBlogId = rsp.blogs[0].id;
        lastBlogId = rsp.blogs[blogCount - 1].id;
      }
    } catch (err) {
      alert(err);
    }
  }

  // 处理分页变化
  async function handleCurrentChange(newPage: number) {
    getBlogs((newPage - 1) * pageSize.value)
  }

  // 页面加载时获取第一页的博客
  onMounted(() => {
    getBlogs(0);
  });

  function handleTagClick(tag: string) {
    alert("Handle Tag Click: " + tag);
  }

  function handleSizeChange(newSize: number) {
    pageSize.value = newSize;
    getBlogs(firstBlogId - 1);
  }

  function handleUpdateCurrentPage(newPage: number) {
    currentPage.value = newPage;
    getBlogs(lastBlogId);
  }

</script>

<style scoped>
  .frame {
    /* min-height: 100vh; */
    /* display: flex; */
    display: block;
    width: 80%;
    margin-left: 10%;
    margin-top: 0%;

    display: flex;
    flex-direction: column;
    gap: 10px; /* 控制博客卡片之间的间距 */

    position: relative; /* 添加相对定位，允许绝对定位的元素相对于 .frame 定位 */
  }

  @media (max-width: 1024px) {
    .frame {
      width: 100%;
      margin-left: 0;
    }
  }

  .blog-card {
    margin-bottom: 2px;
    border-radius: 15%;
    background-color: #f3f1f1;
  }

  .blog-title {
    margin-bottom: 10px;
  }

  .title-url {
    font-size: 20px; /* 调整标题字体大小 */
    color: #333;
    text-decoration: none;
  }

  .blog-meta {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #999;
  }

  .left-info {
    display: flex;
    align-items: center;
  }

  .right-info {
    display: flex;
    align-items: center;
  }

  .info-item {
    margin-left: 10px; /* 增加元素之间的间距 */
  }

  .content-text {
    font-size: 14px; /* 调整内容字体大小 */
    color: #666;
    margin-top: 10px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end; /* 使页码靠右显示 */
  }

  .blog-tags {
    margin: 6px 6px; /* 为标签添加间距 */
  }

  /* 垂直分割线 */
  .el-divider-vertical {
    margin: 0 5px; /* 增加分割线的间距 */
  }

</style>
